package com.upload.spring.boot.chooser;

import com.upload.spring.boot.server.UploadCustomizer;
import com.upload.spring.boot.type.UploadType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lgc
 * @createDate 2020/7/29 - 11:54
 */
public class UploadChooer implements ApplicationContextAware {
     private ApplicationContext applicationContext;
     private Map<UploadType, UploadCustomizer> chooseMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    //根据key获取具体策略对象
    public UploadCustomizer chooseType(UploadType p){
        return chooseMap.get(p);
    }

    @PostConstruct //beans加载完之后运行该方法
    public void registerUploadType(){
        Map<String, UploadCustomizer> map = applicationContext.getBeansOfType(UploadCustomizer.class);
        map.values().forEach(uploadCustomizer->{
            chooseMap.put(uploadCustomizer.getUploadType(),uploadCustomizer);
        });

    }




}
